package com.framework.loippi.plugin.wxapppay;

import com.framework.loippi.cache.ConfigCache;
import com.framework.loippi.envsupport.EnvManager;
import com.framework.loippi.plugin.aliapppay.PayCommon;
import com.framework.loippi.utils.JacksonUtil;
import com.framework.loippi.utils.StringUtils;
import com.framework.loippi.utils.wechat.utils.WeixinUtils;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 微信APP支付
 *
 * @author Administrator
 */
public class WechatMobilePay {

    public static String toPay(PayCommon payCommon) {
        //WXpayConfig.initPayConfig(new HashMap<String, Object>());
        Map<String, String> parameters = getParameterMap(payCommon);
        StringBuilder strBuilder = new StringBuilder();
        strBuilder.append("<xml>");
        Set<String> objSet = parameters.keySet();
        for (Object key : objSet) {
            if (key == null) {
                continue;
            }
            strBuilder.append("<").append(key.toString()).append(">");
            Object value = parameters.get(key);
            strBuilder.append(null == value ? "" : value.toString());
            strBuilder.append("</").append(key.toString()).append(">");
        }
        strBuilder.append("</xml>");
        String xml = WeixinUtils.request(getRequestUrl(), "POST",
                strBuilder.toString()).toString();

        if (StringUtils.isNotEmpty(xml) && xml.indexOf("SUCCESS") != -1) {
            if (xml.indexOf("prepay_id") != -1) {
                String prepayid = WeixinUtils.getJsonValue(xml, "prepay_id");
                Map<String, String> clientMap = makeClientMap(prepayid,
                        parameters.get("nonce_str"));
                return JacksonUtil.toJson(clientMap);
            }
        }
        return null;
    }

    public static Map<String, String> makeClientMap(String prepayid, String nonceStr) {
        HashMap<String, String> parameterMap = new HashMap<String, String>();
        parameterMap.put("appid", ConfigCache.getConfig("wx.open.appId"));
        parameterMap.put("partnerid", ConfigCache.getConfig("wx.open.pay.partnerId"));
        parameterMap.put("prepayid", prepayid);
        parameterMap.put("package", "Sign=WXPay");
        parameterMap.put("noncestr", nonceStr);
        parameterMap.put("timestamp", WeixinUtils.getTimeStamp());
        parameterMap.put("sign", WeixinUtils.sign(
                WeixinUtils.FormatBizQueryParaMap(parameterMap, false),
                ConfigCache.getConfig("wx.open.pay.partnerKey")));
        return parameterMap;
    }


    public static Map<String, String> getParameterMap(PayCommon payCommon) {

        String ipAddress = EnvManager.getUserEnvInfo().getClientIp();

        // 这里notify_url是 支付完成后微信发给该链接信息，可以判断会员是否支付成功，改变订单状态等。
        HashMap<String, String> parameterMap = new HashMap<String, String>();
        parameterMap.put("appid", ConfigCache.getConfig("wx.open.appId"));
        parameterMap.put("body", payCommon.getBody());
        parameterMap.put("mch_id", ConfigCache.getConfig("wx.open.pay.partnerId"));
        parameterMap.put("out_trade_no", payCommon.getOutTradeNo());
        parameterMap.put("total_fee",
                payCommon.getPayAmount().multiply(new BigDecimal(100)).intValue()
                        + "");
        parameterMap.put("notify_url", ConfigCache.getConfig("pay.callback.url") + payCommon.getNotifyUrl());
        parameterMap.put("spbill_create_ip", ipAddress != null ? ipAddress : "8.8.8.8");
        parameterMap.put("nonce_str", WeixinUtils.createNoncestr());
        parameterMap.put("trade_type", "APP");
        parameterMap.put("sign", WeixinUtils.sign(
                WeixinUtils.FormatBizQueryParaMap(parameterMap, false),
                ConfigCache.getConfig("wx.open.pay.partnerKey")));
        return parameterMap;
    }

    public static String getRequestUrl() {
        return "https://api.mch.weixin.qq.com/pay/unifiedorder";
    }
}
